<template>
  <div>
    <el-form class="tl-form" ref="form" :model="model" :rules="rules" label-width="150px" :disabled="disableEditSubmit || disableSave">
      <el-tabs type="border-card" v-model="tabName">
        <el-tab-pane label="立项信息" name="projectbasicinfo">
          <el-row>
            <el-col :span="12">
              <el-form-item label="项目来源" prop="projectsource">
                <el-select v-model="model.projectsource" @change="changeSource" filterable clearable>
                  <el-option v-for="item in codeModel.projectSourceList" :key="item.code" :label="item.name" :value="item.code" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="leadOrChanceLabel" prop="chanceclue">
                <el-input v-model="model.chanceclue" :disabled="true" class="tl-ref-selector">
                  <el-button slot="append" type="primary" icon="el-icon-search" @click="openChanceclueDialog" v-if="!disableSave"></el-button>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="项目编号" prop="projectcode">
                <el-input v-model="model.projectcode" :disabled="true" placeholder="系统自动生成"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="项目经理" prop="projectmanager" :rules="rules.rulesForInfo">
                <el-input v-model="model.projectmanager" :disabled="true"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="项目名称" prop="projectname" :rules="rules.rulesForInfo">
                <el-input v-model="model.projectname" :disabled="midChangePoint && model.projectsource !== '1'"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="可参与金额" prop="participatemoney" :rules="model.projectsource === '1' ? [] : rules.rulesForInfo">
                <el-input-number v-model="model.participatemoney" :disabled="midChangePoint && model.projectsource !== '1'" controls-position="right" :step="1" :min="0" :precision="2" style="width:91%"></el-input-number><span>万元</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="10">
              <el-form-item label="项目级别" prop="projectlevel" :rules="rules.rulesForInfo" style="width: 115%">
                <el-select v-model="model.projectlevel" filterable clearable disabled>
                  <el-option v-for="item in codeModel.projectlevelList" :key="item.code" :label="item.name" :value="item.code" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="2">
              <el-button type="primary" @click="openChangeLevelDialog" :disabled="!model.projectlevel" style="width: 50px;position: relative;right: 0px;top: 0px;float: right">
                <span style="position: relative;left:-4px;">修改</span>
              </el-button>
            </el-col>
            <el-col :span="12">
              <el-form-item label="采购模式" prop="purchasepattern" :rules="model.projectsource === '1' ? [] : rules.rulesForInfo">
                <el-select v-model="model.purchasepattern" filterable clearable @change="changepurchasepattern">
                  <el-option v-for="item in codeModel.MpmPurchasePatternList" :key="item.code" :label="item.name" :value="item.code" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="计划开始日期" prop="planstartdate" :rules="rules.rulesForInfo">
                <el-date-picker v-model="model.planstartdate" type="date" placeholder="例：2021-01-01" value-format="yyyy-MM-dd" @change="planStart">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="计划结束日期" prop="planenddate" :rules="rules.rulesForInfo">
                <el-date-picker v-model="model.planenddate" type="date" placeholder="例：2021-01-01" value-format="yyyy-MM-dd" @change="planEnd">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="创建部门" prop="deptname" :rules="rules.rulesForInfo">
                <tl-ref-dept v-model="model.deptname" :initDisplayData.sync="model.deptname" dataType="code" nameType="fullname" @confirm="onSelectDept" :singleSelect="true" :externalQueryParam="{qry_enabled:1}">
                </tl-ref-dept>
              </el-form-item>
            </el-col>
            <!-- <el-col :span="12">
              <el-form-item label="项目周期" prop="bidcycle">
                <el-input v-model="model.bidcycle" style="width:93%" placeholder="系统自动计算"></el-input><span>天</span>
              </el-form-item>
            </el-col> -->
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="挂网日期" prop="bidbegindate" :required="bidrequired && model.projectsource === '2'">
                <el-date-picker v-model="model.bidbegindate" type="date" placeholder="例：2021-01-01" value-format="yyyy-MM-dd">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="开标日期" prop="bidenddate" :required="bidrequired && model.projectsource === '2'">
                <el-date-picker v-model="model.bidenddate" type="date" placeholder="例：2021-01-01" value-format="yyyy-MM-dd">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="Sponsor" prop="sponsorcode" :rules="rules.rulesForInfo">
                <tl-ref-user v-model="model.sponsorcode" :initDisplayData.sync="model.sponsor" dataType="code" :singleSelect="true">
                </tl-ref-user>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="Owner" prop="ownercode" :rules="rules.rulesForInfo">
                <tl-ref-user v-model="model.ownercode" :initDisplayData.sync="model.owner" dataType="code" :singleSelect="true">
                </tl-ref-user>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="决策组人员" prop="decisionusername" :rules="rules.rulesForInfo">
                <el-input v-model="model.decisionusername" class="tl-ref-selector" disabled>
                  <el-button slot="append" type="primary" icon="el-icon-search" @click="openMpmProjectResourcePoolDialog" v-if="!disableSave"></el-button>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="historyLevel && model.projectlevel !== historyLevel">
            <el-col :span="12">
              <el-form-item label="原项目级别">
                <el-input v-model="historyLevel" class="tl-ref-selector" disabled></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="model.projectlevel && tempprojectlevel && model.projectlevel !== tempprojectlevel && !(model.purchasepattern === '1' && maxLevel === 3)">
            <el-col :span="24">
              <el-form-item label="项目级别调整原因" prop="changelevelreason" :rules="rules.rulesForInfo">
                <el-input v-model="model.changelevelreason" type="textarea" :rows="4" maxlength="1000" show-word-limit>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="model.productrange && model.productrange.length > 0 && Array.isArray(model.productrange)">
            <el-row style="margin-bottom:20px;margin-top:20px;">
              <div>
                <div class="formLine"><span class="formLineTitle">【涉及产品范围】包含产品类别，金额</span></div>
              </div>
            </el-row>
            <el-row v-for="(item,index) in model.productrange" :key="index">
              <el-col :span="12">
                <el-form-item label="产品类别">
                  <el-input v-model="item.productType" disabled class="tl-ref-selector">
                    <el-input v-model="item.productType"></el-input>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="金额">
                  <el-input-number v-model="item.productMoney" controls-position="right" :step="1" :min="0" :precision="2" style="width:91%"></el-input-number><span>万元</span>
                </el-form-item>
              </el-col>
            </el-row>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="项目背景概述" prop="background">
                <el-input v-model="model.background" type="textarea" :rows="4" maxlength="1000" show-word-limit>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="项目目标" prop="target">
                <el-input v-model="model.target" type="textarea" :rows="4" maxlength="1000" show-word-limit></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="总体策划" prop="summary">
                <el-input v-model="model.summary" type="textarea" :rows="4" maxlength="1000" show-word-limit></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-collapse>
            <el-collapse-item title="【单据】申请信息">
              <el-row>
                <el-col :span="12">
                  <el-form-item label="申请人姓名" prop="username" :rules="rules.rulesForInfo">
                    <el-input v-model="model.username" disabled></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="申请人工号" prop="usercode">
                    <el-input v-model="model.usercode" disabled></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="申请人部门" prop="applydeptname">
                    <el-input v-model="model.applydeptname" disabled></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="申请人公司" prop="applyorgname">
                    <el-input v-model="model.applyorgname" disabled></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-collapse-item>
          </el-collapse>
        </el-tab-pane>
        <el-tab-pane label="客户信息" name="projectcustomerinfo">
          <div style="margin-top:1px;margin-left:-20px" class="mancomment">
            <el-row>
              <el-col :span=" 12">
                <el-form-item label="客户名称" prop="clientname" :rules="rules.rulesForCustomeryInfo">
                  <el-input v-model="model.clientname" :disabled="true"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="客户部门" prop="clientdept" :rules="rules.rulesForCustomeryInfo">
                  <el-input v-model="model.clientdept" :disabled="true"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span=" 12">
                <el-form-item label="客户决策链支持度" prop="clientsupport" :rules="rules.rulesForCustomeryInfo">
                  <el-input v-model="model.clientsupport"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="客户需求分析" prop="clientdemand" :rules="rules.rulesForCustomeryInfo">
                  <el-input v-model="model.clientdemand" type="textarea" :rows="6" maxlength="1000" show-word-limit>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="客户决策模式" prop="decisionmode" :rules="rules.rulesForCustomeryInfo">
                  <el-input v-model="model.decisionmode" type="textarea" :rows="6" maxlength="1000" show-word-limit>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-tab-pane>
        <el-tab-pane label="竞争对手" name="projectcompetitorinfo">
          <div style="margin-top:1px;margin-left:-50px" class="mancomment">
            <el-row>
              <el-col :span="24">
                <el-form-item label="主要竞争对手" prop="competitor" :rules="rules.rulesForCompetitorInfo">
                  <el-input v-model="model.competitor" type="textarea" :rows="8" maxlength="1000" show-word-limit>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="SWOT分析" prop="swot" :rules="rules.rulesForCompetitorInfo">
                  <el-input v-model="model.swot" type="textarea" :rows="8" maxlength="1000" show-word-limit></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <tlmpmProject-manager-pool-ref ref="mpmProjectManagerPoolRef" @confirm="getMpmProjectManagerData" :isSingleSelect="true" :externalQueryParam="externalMQueryParamForPool">
    </tlmpmProject-manager-pool-ref>
    <tlmpmProject-resource-pool-ref ref="mpmProjectResourcePoolRef" @confirm="getMpmProjectResourceData" :fieldKey="'usercode'" :externalSelectedRowKeys="model.decisionusercode" :isSingleSelect="false" :externalQueryParam="externalDQueryParamForPool">
    </tlmpmProject-resource-pool-ref>
    <tlchange-ref ref="changeRef" :labelName="leadOrChanceLabel" @confirm="getChanceclueData" :externalQueryParam="{ projectsource: model.projectsource }" :chanceclue2="model.chanceclue" :isSingleSelect="true" :fieldKey="rowKeyStr">
    </tlchange-ref>
    <tlChangeLevel-ref ref="changeLevelRef" @confirm="confirmChangeLevel"></tlChangeLevel-ref>
  </div>
</template>

<script>
  /** mixins */
  import { mixin_approval_edit } from '@tapui/mixins/mixin_approval_edit'
  import { mixin_page_fields_custom } from '@misui/mixins/mixin_page_fields_custom'
  /** 子组件 */
  import { validateNull } from '@tapui/utils/validate'
  import tlmpmProjectManagerPoolRef from '@/views/mpm/mpmProjectManagerPool/refList'
  import tlmpmProjectResourcePoolRef from '@/views/mpm/mpmProjectResourcePool/refList'
  import tlchangeRef from '@/views/mpm/mpmProject/refListChange'
  import tlChangeLevelRef from "./changeLevelCompent"
  /** 工具类 */
  import { putAction, getAction, postAction, deleteAction } from '@tapui/utils/http'
  /** VUE配置 */
  export default {
    mixins: [mixin_approval_edit, mixin_page_fields_custom],
    components: { tlmpmProjectManagerPoolRef, tlmpmProjectResourcePoolRef, tlchangeRef, tlChangeLevelRef },
    data() {
      var validateForTab = (rule, value, callback) => {
        if (!value) {
          this.tabName = rule.tabname
          return callback(new Error('请输入内容'))
        } else {
          return callback()
        }
      }
      return {
        bidrequired: true,
        moduleTitle: '项目立项',
        urlPrefix: '/mpm/projectpolymerization/',
        url: {
          // 额外的url
          queryOrgByDeptId: '/mpm/project/queryOrgByDeptId',
          list: '/cbo/approvalNodeIns/list',
          changeList: '/mpm/project/changeList'
        },
        tabName: 'projectbasicinfo',
        sorterInfo: {
          // 排序参数
          sidx: 'id',
          sord: 'desc'
        },
        midChangePoint: true,
        datas: [],
        pageInfo: {
          // 分页参数
          currentPage: 1, // 当前页面
          pageSize: 10, // 每页记录数
          pageSizes: ['10', '50', '100'],
          totalCount: 0 // 总数
        },
        rowKeyStr: 'CODE',
        loading: false,
        visible: false,
        listMode: true,
        externalMQueryParamForPool: {},
        externalDQueryParamForPool: {},
        // 项目立项规则校验重写
        addRules: {
          // 基本信息TAB表单校验
          rulesForInfo: [
            { validator: validateForTab, tabname: 'projectbasicinfo', trigger: 'change' },
            { required: 'true', message: '请输入内容', trigger: 'change' }
          ],
          // 案例概述TAB表单验证
          rulesForCustomeryInfo: [
            { validator: validateForTab, tabname: 'projectcustomerinfo', trigger: 'change' },
            { required: 'true', message: '请输入内容', trigger: 'change' }
          ],
          rulesForCompetitorInfo: [
            { validator: validateForTab, tabname: 'projectcompetitorinfo', trigger: 'change' },
            { required: 'true', message: '请输入内容', trigger: 'change' }
          ]
        },
        // 项目级别默认编码值，根据选择的机会点确定
        tempprojectlevel: '',
        // 项目级别默认显示值，根据选择的机会点确定
        tempdispprojectlevel: '',
        // CEO信息
        tempdecisionusercode: '',
        tempdecisionusername: '',
        // 项目等级，例：网级、省级等
        maxLevel: -1
      }
    },
    props: {
    },
    computed: {
      leadOrChanceLabel() {
        if (this.model.projectsource && this.codeModel.projectSourceList) {
          return this.codeModel.projectSourceList.find(item => item.code === this.model.projectsource).name
        } else {
          return '线索/机会点'
        }
      },
      historyLevel() {
        if (this.model.levelhistory) {
          return JSON.parse(this.model.levelhistory.replace(/\//g, "")).oldprojectlevel
        } else {
          return ''
        }
      }
    },
    methods: {
      changepurchasepattern(value) {
        if (value === '8') {
          this.bidrequired = false
        } else {
          this.bidrequired = true
        }
      },
      planStart(e) {
        var a = new Date(this.model.planstartdate)
        var b = new Date()
      },
      planEnd(e) {
        if (this.model.planstartdate === '' || typeof this.model.planstartdate === 'undefined') {
          this.$tap.alert('请先选择计划开始日期！', 'warning')
          this.$set(this.model, "planenddate", '')
          this.$set(this.model, "bidcycle", '')
          return
        }
        var c = new Date(this.model.planenddate).getTime()
        var d = new Date(this.model.planstartdate).getTime()
        if (c < d) {
          this.$tap.alert('开始日期不得大于结束日期。', 'warning')
          this.$set(this.model, "planenddate", '')
          this.$set(this.model, "bidcycle", '')
          return
        }
        var a = c - d
        var days = Math.ceil(a / (1000 * 3600 * 24)) + 1
        this.$set(this.model, 'bidcycle', days)
        // 计划结束日期存储为选择日期的的23：59：59
        let date = new Date(c)
        let timeDate = ""
        let Y = date.getFullYear() + '-'
        let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
        let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' '
        let h = 23 + ':'
        let m = 59 + ':'
        let s = 59
        timeDate = Y + M + D + h + m + s
        this.$set(this.model, 'planenddate', timeDate)
      },
      assignDefaultValue() {
        if (this.isAdd) {
          this.$set(this.model, 'applyorgcode', this.org.code)
          this.$set(this.model, 'applyorgname', this.org.name)
          this.$set(this.model, 'orgcode', this.org.code)
          this.$set(this.model, 'applydeptcode', this.dept.code)
          // this.$set(this.model, 'deptcode', this.dept.code)
          this.$set(this.model, 'applydeptname', this.dept.fullname)
          this.$set(this.model, 'usercode', this.user.code)
          this.$set(this.model, 'username', this.user.name)
          // this.$set(this.model, 'projectmanagercode', this.user.code)
          // this.$set(this.model, 'projectmanager', this.user.name)
          this.$set(this.model, 'docdate', new Date())
          this.$set(this.model, 'applydate', new Date())
          this.$set(this.model, 'projecttype', '0')
        }
      },
      // loaded() {
      //   页面加载完毕执行
      //     if (!this.isAdd && this.model.docno) {
      //       this.title = this.title + `（单据编号：${this.model.docno}）`
      //     }
      // },
      beforeApproval() {
        if (
          this.model.projectmanagercode === this.model.sponsorcode ||
          this.model.projectmanagercode === this.model.ownercode ||
          this.model.sponsorcode === this.model.ownercode
        ) {
          this.$tap.alert('项目经理、sponsor和owner不能重复，请确认！', 'warning')
          return false
        } else {
          return true
        }
      },
      /** 提交审批 */
      doSubmitApproval() {
        if (!this.url.submit) {
          this.$tap.alert('请设置审批地址!', 'warning')
          return
        }
        let fileValidate = true
        this.$refs.form.validate((valid) => {
          if (!valid) {
            fileValidate = false
          }
        })
        if (!fileValidate) {
          return
        }
        if (!this.beforeApproval()) {
          return
        }
        this.submitLoading = true
        this.$tap
          .confirm('确定提交审批吗？提交后，单据内容不可修改！')
          .then((_) => {
            this.$set(this.model, 'projectstate', '0')
            if (this.isAdd) {
              this.saveLoading = true
              // 增加唯一单号
              this.$set(this.model, 'billuid', this.uid)
              postAction(this.url.add, this.model)
                .then((res) => {
                  if (res.success) {
                    this.$tap.message('添加成功', 'success')
                    this.queryData(res.result.id)
                    this.isAdd = false
                    putAction(this.url.submit, this.model).then((res) => {
                      if (res.success) {
                        this.$emit('refresh')
                        this.$tap.message(res.message, 'success')
                        this.queryData(this.model.id).then((_) => {
                          this.loaded()
                        })
                        this.afterApproval()
                      } else {
                        this.$tap.alert(res.message, 'warning')
                      }
                      this.submitLoading = false
                    })
                  } else {
                    this.$tap.alert(res.message, 'warning')
                  }
                  this.afterSubmit()
                  this.saveLoading = false
                })
                .catch((err) => {
                  this.saveLoading = false
                })
            } else {
              this.saveLoading = true
              putAction(this.url.edit, this.model)
                .then((res) => {
                  if (res.success) {
                    putAction(this.url.submit, this.model).then((res) => {
                      if (res.success) {
                        this.$emit('refresh')
                        this.$tap.message(res.message, 'success')
                        this.queryData(this.model.id).then((_) => {
                          this.loaded()
                        })
                        this.afterApproval()
                      } else {
                        this.$tap.alert(res.message, 'warning')
                      }
                      this.submitLoading = false
                    })
                  } else {
                    this.$tap.alert(res.message, 'warning')
                  }
                  this.afterSubmit()
                  this.saveLoading = false
                })
                .catch((err) => {
                  this.saveLoading = false
                })
            }
          })
          .catch((_) => {
            this.submitLoading = false
          })
      },
      /** 执行编辑提交 */
      doEdit() {
        this.saveLoading = true
        putAction(this.url.edit, this.model)
          .then((res) => {
            if (res.success) {
              this.$emit('refresh')
            } else {
              this.$tap.alert(res.message, 'warning')
            }
            this.afterSubmit()
            this.saveLoading = false
          })
          .catch((err) => {
            this.saveLoading = false
          })
      },
      // 选择项目所属部门
      onSelectDept(selectedDepts) {
        const selectedDept = selectedDepts[0]
        const { id, code, fullname } = selectedDept
        this.$set(this.model, 'deptcode', code)
        this.$set(this.model, 'deptname', fullname)
        const param = {
          deptId: id
        }
        getAction(this.url.queryOrgByDeptId, param).then((res) => {
          if (res.success) {
            const { code: orgcode, name: orgname } = res.result
            this.$set(this.model, 'orgcode', orgcode)
            this.$set(this.model, 'orgname', orgname)
          } else {
            this.$tap.alert('已选部门关联公司信息错误，请联系系统管理员')
          }
        })
      },
      open() {
        this.model = {}
        this.$nextTick(() => {
          this.getFieldsCustomSetting('projectpolymerization', 'el-form')
          this.$refs.form.clearValidate()
          if (this.isAdd === true) {
            this.title = '新增' + this.moduleTitle
            // 需要添加重复判断
            if (this.$store.getters.param.isAvoidRepeat === true) {
              this.queryBillUid()
            }
            if (this.isQueryInitData === true) {
              // 后台进行数据初始化
              this.queryInitData().then((_) => {
                this.assignDefaultValue()
                this.loaded()
              })
            } else {
              // 前台进行数据初始化
              this.$set(this.model, 'enabled', 1)
              this.$set(this.model, 'sortcode', 0)
              this.assignDefaultValue()
              this.loaded()
            }
          } else if (this.disableEditSubmit === false) {
            this.title = '编辑' + this.moduleTitle
            this.queryData(this.id).then((_) => {
              // 获取项目等级
              this.getMaxLevel()
              this.loaded()
            })
          } else {
            this.title = '查看' + this.moduleTitle
            this.queryData(this.id).then((_) => {
              // 获取项目等级
              this.getMaxLevel()
              this.loaded()
            })
          }
        })
        this.datas = []
        this.loadData({ currentPage: 1 })
      },
      /** 加载审批历史列表数据 */
      loadData(paramMap) {
        if (validateNull(paramMap) === false && Object.keys(paramMap).indexOf('currentPage') > -1) {
          this.pageInfo.currentPage = paramMap['currentPage']
        }
        // 查询条件
        this.sorterInfo.sidx = 'approvaldate'
        var params = this.getQueryParams()
        // 数据查询
        this.loading = true
        getAction(this.url.list, params)
          .then((res) => {
            if (res.success) {
              this.datas = res.result.dataList
              this.pageInfo.totalCount = res.result.totalCount
            } else {
              this.$tap.alert(res.message, 'warning')
            }
            this.loading = false
          })
          .catch((err) => {
            this.loading = false
          })
      },
      /** 执行查询 */
      doQuery() {
        this.loadData({ currentPage: 1 })
      },
      /** 获取查询参数 */
      getQueryParams() {
        let param = {
          qry_sourcetype: 'MpmProject',
          qry_sourceid: 0
        }
        if (!this.isAdd) {
          param.qry_sourceid = this.id
        }
        Object.assign(param, this.sorterInfo)
        param.currentPage = this.pageInfo.currentPage
        param.pageSize = this.pageInfo.pageSize
        return param
      },
      /** 表格列排序 */
      doSortChange(columnInfo, prop, order) {
        if (columnInfo.column === null) {
          return
        }
        // 不排序
        if (validateNull(columnInfo.order)) {
          this.loadData({})
          return
        }
        // 升序或者降序排序
        if (columnInfo.column.sortBy) {
          this.sorterInfo.sidx = columnInfo.column.sortBy
        } else {
          this.sorterInfo.sidx = columnInfo.prop
        }
        this.sorterInfo.sord = columnInfo.order.replace('ending', '')
        this.loadData({})
      },
      /** 每页大小改变 */
      doChangeSize(val) {
        if (this.pageInfo.pageSize !== val) {
          this.pageInfo.pageSize = val
          this.pageInfo.currentPage = 1
          this.loadData({})
        }
      },
      /** 页面跳转 */
      doChangeIndex(val) {
        if (this.pageInfo.currentPage !== val) {
          this.pageInfo.currentPage = val
          this.loadData({})
        }
      },
      drawDiagram(map) {
        /* eslint-disable*/
        $('#history-myflow').html('')
        let restore = map.strdiagram
        restore = restore.replace(/'/g, '"')
        if (restore !== '') {
          restore = JSON.parse(restore)
        }
        let history = map.strhistory
        history = history.replace(/'/g, '"')
        history = history.replace(/activeRects/g, '"activeRects"')
        history = history.replace(/historyRects/g, '"historyRects"')
        history = history.replace(/rects/g, '"rects"')
        history = history.replace(/paths/g, '"paths"')
        history = history.replace(/code/g, '"code"')
        if (history !== '') {
          history = JSON.parse(history)
        }
        $('#history-myflow').myflow(
          $.extend(false, {
            basePath: '',
            restore: restore,
            editable: false,
            ...history
          })
        )
      },
      // 项目级别变更后，清空项目经理和决策组--2-7todo 暂时取消
      clear() {
        if (this.model.projectmanagercode || this.model.decisionusercode) {
          this.$set(this.model, 'projectmanagercode', '')
          this.$set(this.model, 'projectmanager', '')
          this.$set(this.model, 'decisionusercode', '')
          this.$set(this.model, 'decisionusername', '')
        }
      },
      /** 打开项目经理参照 */
      openMpmProjectManagerPoolDialog() {
        const { projectlevel, projecttype } = this.model
        if (!projectlevel) {
          this.$tap.alert('请先选择项目级别！', 'warning')
          this.$refs.mpmProjectManagerPoolRef.visible = false
        } else {
          this.externalMQueryParamForPool = {
            projectlevel: projectlevel,
            projecttype: projecttype
          }
          this.$refs.mpmProjectManagerPoolRef.visible = true
        }
      },
      /** 获取项目经理参照数据 */
      getMpmProjectManagerData(selectionRow, selectKey, selectionValue) {
        this.$set(this.model, 'projectmanagercode', selectionRow.managercode)
        this.$set(this.model, 'projectmanager', selectionRow.managername)
      },
      /** 打开决策组成员参照 */
      openMpmProjectResourcePoolDialog() {
        const { projectlevel, projecttype } = this.model
        if (!projectlevel) {
          this.$tap.alert('请先选择项目级别！', 'warning')
          this.$refs.mpmProjectResourcePoolRef.visible = false
        } else {
          this.externalDQueryParamForPool = {
            projectlevel: projectlevel,
            projecttype: projecttype
          }
          this.$refs.mpmProjectResourcePoolRef.visible = true
        }
      },
      /** 获取决策组成员参照数据 */
      getMpmProjectResourceData(selectionRow, selectKey, selectionValue) {
        // 将CEO数据分割为数组
        let tempdecisionusercodeArr = this.tempdecisionusercode.split(',')
        let resultcodes = this.tempdecisionusercode
        let resultnames = this.tempdecisionusername
        if (Array.isArray(selectionRow)) {
          if (selectionRow.length > 0) {
            let code = []
            let name = []
            selectionRow.forEach((element) => {
              // 移除选择的人员中的CEO数据
              if (tempdecisionusercodeArr.indexOf(element.usercode) < 0) {
                code.push(element.usercode)
                name.push(element.username)
              }
            })
            if (code.length > 0 && name.length > 0) {
              resultcodes += code.join(',') + ','
              resultnames += ',' + name.join(',')
            }
          }
        } else {
          if (tempdecisionusercodeArr.indexOf(selectionRow.usercode) < 0) {
            resultcodes += selectionRow.usercode + ','
            resultnames += ',' + selectionRow.username
          }
        }
        this.$set(this.model, 'decisionusercode', resultcodes)
        this.$set(this.model, 'decisionusername', resultnames)
      },
      /** 打开机会点参照 */
      openChanceclueDialog() {
        if (!this.model.projectsource) {
          this.$tap.alert('请先选择项目来源！', "warning")
        } else {
          this.$refs.changeRef.visible = true
        }
      },
      /** 获取机会点参照数据 */
      getChanceclueData(selectionRow, selectKey, selectionValue) {
        var participatemoney = 0
        //单个机会点
        if (!Array.isArray(selectionRow)) {
          // 项目名称和可参与金额都不可编辑
          this.midChangePoint = true
          this.$set(this.model, 'chanceclue', selectionRow.CODE)
          this.$set(this.model, 'projectname', selectionRow.PROJECT_NAME)
          this.$set(this.model, 'projectmanager', selectionRow.GARDENER_NAME)
          this.$set(this.model, 'projectmanagercode', selectionRow.GARDENER_CODE)
          this.$set(this.model, 'deptname', selectionRow.DEPT_COMMON_CODE_1NAME)
          //从机会点获取到的creator_dept_code 作为创建部门编码(deptcode)，根据创建部门编码，走审批
          this.$set(this.model, 'deptcode', selectionRow.CREATOR_DEPT_CODE)
          this.$set(this.model, 'participatemoney', selectionRow.OUR_PROCDUCT_FUND)
          this.$set(this.model, 'clientname', selectionRow.CLIENT_NAME)
          this.$set(this.model, 'clientdept', selectionRow.CLIENT_DEPT_NAME)
          //获取产品类型，拼装产品金额，请求报文为json数组
          var proType = [];
          if (selectionRow.CATALOG) {
            proType = selectionRow.CATALOG.split(",")
          }
          var productScotts = [];
          proType.forEach((item, index) => {
            var productScott = {
              productType: item,
              productMoney: ''
            }
            productScotts.push(productScott)
          })
          this.$set(this.model, 'productrange', productScotts)
          //多个机会点情况
        } else {
          //项目名称，可参与金额须手填
          this.midChangePoint = selectionRow.length <= 1
          var chanceclue = ''
          var productScotts = []
          var unProductTypes = []
          //循环取值
          selectionRow.forEach((item, index) => {
            this.$set(this.model, 'projectname', item.PROJECT_NAME)
            this.$set(this.model, 'projectmanager', item.GARDENER_NAME)
            this.$set(this.model, 'projectmanagercode', item.GARDENER_CODE)
            this.$set(this.model, 'deptname', item.DEPT_COMMON_CODE_1NAME)
            //从机会点获取到的creator_dept_code 作为创建部门编码(deptcode)，根据创建部门编码，走审批
            this.$set(this.model, 'deptcode', item.CREATOR_DEPT_CODE)
            this.$set(this.model, 'participatemoney', item.OUR_PROCDUCT_FUND)
            this.$set(this.model, 'clientname', item.CLIENT_NAME)
            this.$set(this.model, 'clientdept', item.CLIENT_DEPT_NAME)
            participatemoney = participatemoney + parseFloat(item.OUR_PROCDUCT_FUND)
            this.$set(this.model, 'participatemoney', participatemoney)
            //填充机会点
            if (chanceclue.length > 0) {
              chanceclue = chanceclue + "," + item.CODE
            } else {
              chanceclue = item.CODE
            }
            //填充涉及产品范围，获取产品类型，拼装产品金额，请求报文为json数组
            var proType = [];
            if (item.CATALOG) {
              proType = item.CATALOG.split(",")
            }
            for (var i in proType) {
              unProductTypes.push(proType[i])
            }
          })
          var unqProType = []
          unProductTypes.forEach((item, index) => {
            if (unqProType.indexOf(unProductTypes[index]) == -1) {
              unqProType.push(item);
            }
          })
          //产品类别是数组非字符串情况下，填充数据
          if (unProductTypes instanceof Array) {
            // 机会点数据填充
            unqProType.forEach((item, index) => {
              var productScott = {
                productType: item,
                productMoney: ''
              }
              productScotts.push(productScott)
            })
          }
          this.$set(this.model, 'productrange', productScotts)
          this.$set(this.model, 'chanceclue', chanceclue)
        }
        this.setValueOfLevelByChance(selectionRow)
      },
      /** 按照总金额和客户级别给项目级别赋值 **/
      setValueOfLevelByChance(row) {
        let totalFund = 0
        let levelList = []
        if (Array.isArray(row)) {
          row.forEach(item => {
            totalFund += Number(item.OUR_PROCDUCT_FUND)
            levelList.push(Number(item.CLIENT_LEVEL))
          })
        } else {
          totalFund += Number(row.OUR_PROCDUCT_FUND)
          levelList.push(Number(row.CLIENT_LEVEL))
        }
        levelList.sort((a, b) => a - b)
        let maxLevel = levelList[levelList.length - 1]
        // 根据客户级别分类判断，具体客户类别编码按照MMS系统的ClientLevel编码而定
        // 如果是网级
        if (maxLevel >= 4) {
          // 大于等于500万为A级
          if (totalFund >= 500) {
            this.tempprojectlevel = '0'
            this.tempdispprojectlevel = 'A'
          } else if (totalFund >= 100) {
            // 100-500万为B级
            this.tempprojectlevel = '1'
            this.tempdispprojectlevel = 'B'
          } else {
            // 100万以下为C级
            this.tempprojectlevel = '2'
            this.tempdispprojectlevel = 'C'
          }
        } else if (maxLevel >= 3) {
          // 如果是省级
          if (totalFund >= 100) {
            // 大于等于100万为B级
            this.tempprojectlevel = '1'
            this.tempdispprojectlevel = 'B'
          } else {
            // 100万以下为C级
            this.tempprojectlevel = '2'
            this.tempdispprojectlevel = 'C'
          }
        } else if (maxLevel >= 1) {
          // 如果是市县级
          if (totalFund >= 100) {
            // 大于等于100万为C级
            this.tempprojectlevel = '2'
            this.tempdispprojectlevel = 'C'
          } else {
            // 100万以下为D级
            this.tempprojectlevel = '3'
            this.tempdispprojectlevel = 'D'
          }
        }
        // 如果金额为0则将等级置为D
        if (totalFund <= 0) {
          this.tempprojectlevel = '3'
          this.tempdispprojectlevel = 'D'
        }
        this.$set(this.model, 'projectlevel', this.tempprojectlevel)
        this.$set(this.model, 'projectdefaultlevel', this.tempprojectlevel)
      },
      /** 执行新增提交 */
      doAdd() {
        this.saveLoading = true
        // 增加唯一单号
        this.$set(this.model, 'billuid', this.uid)
        postAction(this.url.add, this.model)
          .then((res) => {
            if (res.success) {
              this.$tap.message('添加成功', 'success')
              this.queryData(res.result.id).then((_) => {
                this.loaded()
              })
              this.isAdd = false
            } else {
              this.$tap.alert(res.message, 'warning')
            }
            // this.afterSubmit()
            this.saveLoading = false
          })
          .catch((err) => {
            this.saveLoading = false
          })
      },
      //数据库字符串对象去特殊字符
      loaded() {
        if (this.model.productrange && !Array.isArray(this.model.productrange)) {
          var arrStr = this.model.productrange
          arrStr.replace(/\//g, "");
          this.model.productrange = JSON.parse(arrStr)
        }
        // 通过项目级别编码为项目级别显示值赋值
        if (this.model.projectlevel && !this.model.projectdefaultlevel && this.codeModel.projectlevelList) {
          let tempLevelData = this.codeModel.projectlevelList.find(item => item.code === this.model.projectlevel)
          // 若项目默认级别为空则为tempprojectlevel和tempdispprojectlevel赋值
          this.tempprojectlevel = this.model.projectlevel
          this.tempdispprojectlevel = tempLevelData.name
        }
        // 通过项目默认等级为tempprojectlevel和tempdispprojectlevel赋值
        if ((this.model.projectdefaultlevel || this.model.projectdefaultlevel === '0') && this.codeModel) {
          let tempDefaulLevelData = this.codeModel.projectlevelList.find(item => item.code === this.model.projectdefaultlevel)
          this.tempprojectlevel = this.model.projectdefaultlevel
          this.tempdispprojectlevel = tempDefaulLevelData.name
        }
        // 给midChangePoint赋初始值
        if (this.model.chanceclue) {
          this.midChangePoint = this.model.chanceclue.split(',') <= 1
        }
      },
      close() {
        this.tempprojectlevel = ''
        this.tempdispprojectlevel = ''
        this.maxLevel = -1
      },
      /** 打开调整项目级别的弹框 **/
      openChangeLevelDialog() {
        this.$refs.changeLevelRef.projectlevelList = this.codeModel.projectlevelList
        this.$refs.changeLevelRef.dispprojectdefaultlevel = this.tempdispprojectlevel
        this.$set(this.$refs.changeLevelRef.model, 'projectlevel', this.model.projectlevel)
        this.$set(this.$refs.changeLevelRef.model, 'dispprojectlevel', this.codeModel.projectlevelList.find(item => item.code === this.model.projectlevel).name)
        this.$set(this.$refs.changeLevelRef.model, 'changelevelreason', this.model.changelevelreason)
        this.$refs.changeLevelRef.visible = true
      },
      /** 填写调整项目等级原因后回写数据 **/
      confirmChangeLevel(data) {
        this.$set(this.model, 'projectlevel', data.projectlevel)
        this.$set(this.model, 'changelevelreason', data.changelevelreason)
      },
      afterSubmit() {
        console.log(this.model.productrange)
        this.loaded()
      },
      /** PMO标准化审批前调用 **/
      saveInfo(resolve, reject) {
        putAction(this.url.edit, this.model)
          .then(res => {
            if (res.success) {
              this.$emit('refresh')
              resolve()
            } else {
              this.$tap.alert(res.message, 'warning')
              reject()
            }
          })
          .catch(err => {
            this.$tap.alert('修改项目信息失败，请联系系统管理员', 'warning')
            reject()
          })
      },
      /** 修改项目来源时将机会点/线索编号、项目名称、项目金额、默认等级、级别调整原因和其他中间变量清空 **/
      changeSource(select) {
        this.$set(this.model, 'chanceclue', '')
        this.$set(this.model, 'projectname', '')
        this.$set(this.model, 'participatemoney', '')
        this.$set(this.model, 'projectdefaultlevel', '')
        this.$set(this.model, 'changelevelreason', '')
        this.$set(this.model, 'projectlevel', '')
        this.$set(this.model, 'productrange', [])
        this.tempprojectlevel = ''
        this.tempdispprojectlevel = ''
      },
      /** 获取项目等级，例网级、省级 **/
      getMaxLevel() {
        let param = {
          currentPage: 1,
          pageSize: 500,
          projectsource: this.model.projectsource,
          sidx: 'sortcode',
          sord: 'asc',
          usercode: this.user.code
        }
        if (this.model.chanceclue) {
          getAction(this.url.changeList, param).then((res) => {
            if (res.success) {
              // 当前用户已选择的线索/机会点
              let codes = this.model.chanceclue.split(',')
              // 当前用户所有的线索/机会点
              res.result.dataList.forEach(item => {
                if (codes.find(code => code === item.CODE)) {
                  // 取客户等级最大的作为项目等级
                  this.maxLevel = Math.max(this.maxLevel, Number(item.CLIENT_LEVEL))
                }
              })
            } else {
              this.$tap.alert('获取线索/机会点列表错误，请联系管理员')
            }
          })
        }
      }
    }
  }
</script>
<style scoped>
  .formLine {
    position: relative;
    margin: 0 auto;
    width: 900px;
    height: 1px;
    background-color: #d4d4d4;
    text-align: center;
    font-size: 16px;
    color: rgba(101, 101, 101, 1);
  }
  .formLineTitle {
    position: absolute;
    left: 12%;
    font-family: 'kaiTi';
    background-color: #ffffff;
    padding: 0 15px;
    transform: translateX(-50%) translateY(-50%);
  }
</style>
